<template>
  <div>
    <h1>{{ launchInfo.launchName }}</h1>
    <el-divider></el-divider>
    <div class="info-box">
      <div>
        <img style="width:150px;height:150px" :src="launchInfo.logo" alt="" />
        <p>{{ launchInfo.launchName }}</p>
      </div>
      <div style="text-align: left; flex: 2">
        <p>
          <span class="left">appId-ID：</span
          ><span class="left-main">{{ launchInfo.appId }}</span
          ><span class="right">最近上线时间：</span
          ><span>{{ launchInfo.onlineTime }}</span>
        </p>
        <p>
          <span class="left">最新版本：</span
          ><span class="left-main">{{
            `${launchInfo.version}（${launchInfo.versionNumber}）`
          }}</span
          ><span class="right">上线学校：</span
          ><span>{{ launchInfo.onlineSchool }}所</span>
        </p>
        <p>
          <span class="left">最近发布时间：</span
          ><span class="left-main">{{ launchInfo.issueTime }}</span
          ><span class="right">上架APP：</span
          ><span>{{ launchInfo.appNumber }}个</span>
        </p>
      </div>
      <div>
        <el-button type="primary" @click="viewApp">APP管理</el-button>
        <el-button @click="dialogFormVisible = true" type="primary"
          >发布新版本</el-button
        >
      </div>
    </div>
    <el-divider></el-divider>
    <div>
      <h1>Launch调试口令</h1>
      <div>
        <span
          >当前口令：<el-input
            minlength="6"
            style="width: 200px"
            v-model="launchCode"
            autocomplete="off"
          ></el-input
        ></span>
        <el-button size="mini" type="primary" @click="randomCode()"
          >随机生成</el-button
        >
        <el-button size="mini" type="primary" @click="updateCodeStatus()"
          >确认使用</el-button
        >
        <el-button
          size="mini"
          type="primary"
          @click="onoffCodeStatus(launchCodeStatus ? false : true)"
          >{{
            launchCodeStatus ? '已开启，点击关闭' : '已关闭，点击开启'
          }}</el-button
        >
      </div>
    </div>
    <el-divider></el-divider>
    <h1>
      版本管理 &nbsp;&nbsp;<span style="font-size: 14px; font-weight: normal"
        >上线版本： {{ pagination.total }}个、&nbsp;上线学校：{{
          launchInfo.onlineSchool
        }}所、&nbsp;&nbsp;用户数：{{ launchInfo.userNumber }}台</span
      >
    </h1>
    <el-divider></el-divider>
    <div>
      <el-table :data="launchList" style="width: 100%">
        <el-table-column label="版本">
          <template slot-scope="scope">
            <span>{{
              `${scope.row.version}（${scope.row.versionNumber}）`
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上线学校">
          <template slot-scope="scope">
            <span>{{ scope.row.schoolNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新内容">
          <template slot-scope="scope">
            <pre>{{ scope.row.remark }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="是否强制更新">
          <template slot-scope="scope">
            <span>{{ scope.row.forceUpdateStatus ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最近上线时间">
          <template slot-scope="scope">
            <span>{{ scope.row.onlineTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新情况">
          <template slot-scope="scope">
            <span>{{ scope.row.updateUser + '/' + scope.row.totalUser }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="onlineStuVisibleFn(scope.$index, scope.row)"
              >版本上线</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      >
      </el-pagination>
    </div>
    <el-divider></el-divider>
    <h1>上线学校列表</h1>
    <el-divider></el-divider>
    <div>
      <el-form label-width="80px" :inline="true">
        <el-form-item label="学校名称">
          <el-input
            v-model="search.name"
            placeholder="请输入学校名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="schoolList" style="width: 100%">
        <el-table-column label="学校">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用版本">
          <template slot-scope="scope">
            <span>{{ scope.row.launchVersion }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最近更新">
          <template slot-scope="scope">
            <span>{{ scope.row.updateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="viewSchool(scope.row)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChangeSchool"
        @current-change="handleCurrentChangeSchool"
        :page-size="schoolPagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="schoolPagination.total"
      >
      </el-pagination>
    </div>
    <el-dialog title="发布新版本" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="安装包" :label-width="formLabelWidth">
          <p style="margin: 0" v-if="fileName">{{ fileName }}</p>
          <el-upload
            action
            :http-request="importObj"
            :before-upload="beforeUploadImg"
            :show-file-list="false"
          >
            <el-button type="primary" :loading="uploadLoading" class="u-btn">{{
              form.downloadUrl ? '重新上传' : '上传安装包'
            }}</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item
          prop="version"
          label="版本号"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.version" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          prop="versionNumber"
          label="构建号"
          :label-width="formLabelWidth"
        >
          <el-input
            type="number"
            v-model="form.versionNumber"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="forceUpdateStatus"
          label="是否强制更新"
          :label-width="formLabelWidth"
        >
          <el-switch
            v-model="form.forceUpdateStatus"
            active-text="开"
            inactive-text="关"
            active-value="1"
            inactive-value="0"
          >
          </el-switch>
        </el-form-item>
        <el-form-item
          prop="remark"
          label="更新内容"
          :label-width="formLabelWidth"
        >
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            v-model="form.remark"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="launchAdd">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="版本上线" :visible.sync="onlineStuVisible">
      <online-box-stu @cancel="selectCancel" @change="selectChange" />
    </el-dialog>
  </div>
</template>
<script>
// import base from '@/views/base.vue'
import {
  queyEnumByTableName,
  tableUpdate,
  downloadTemplateFile,
  importData
} from '@/api/api.js'
import {
  getLaunchInfo,
  getLaunchList,
  getSchoolList,
  onlineLaunch,
  launchAdd,
  debugQuery,
  debugUpdate,
  debugOnoff
} from '@/api/launch'
import {
  adminschoollist,
  enumschoolall,
  adminimportschoolExport
} from '@/api/lcmapi.js'
import OnlineBoxStu from './components/online-box-stu.vue'
import { ossUpload } from '@/api/api.js'
import { random } from 'utility'
export default {
  name: 'launch-manage-stu',
  data () {
    return {
      launchCode: null,
      launchCodeStatus: false,
      uploadLoading: false,
      fileName: '',
      onlineStuVisible: false,
      dialogFormVisible: false,
      form: {
        remark: '',
        versionNumber: '',
        version: '',
        downloadUrl: '',
        forceUpdateStatus: 0
      },
      formLabelWidth: '120px',
      currentPage4: 4,
      search: {
        name: ''
      },
      launchType: 1,
      multipleSelection: [],
      selectArr: {
        schoolType: [], // 学校性质
        level: [], // 学校等级
        studentScale: [], // 学生规模
        isOpen: [], // 状态
        coverageGrade: [] // 覆盖年级
      },
      pagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      schoolPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      mode: '',
      addSchoolDialog: false,
      salesOperationDialog: false,
      list: [],
      launchInfo: {},
      launchList: [],
      schoolList: [],
      selectLaunch: null,
      rules: {
        downloadUrl: [{ required: true }],
        remark: [
          { required: true, message: '请输入更新内容', trigger: 'blur' }
        ],
        versionNumber: [
          { required: true, message: '请输入构建号', trigger: 'blur' }
        ],
        forceUpdateStatus: [
          { required: true, message: '请选择是否强制更新', trigger: 'change' }
        ],
        version: [{ required: true, message: '请输入版本号', trigger: 'blur' }]
      }
    }
  },
  components: {
    OnlineBoxStu
  },
  activated () {
    this.$store.dispatch('common/saveRegion')
    this.search.area = []
    this.search.area[0] = 330000
    this.getDataList('', '', '', '')
    debugQuery({}).then(res => {
      if (!res[0]) {
        this.launchCode = res[1].data.command
        this.launchCodeStatus = res[1].data.on
      }
      console.log('res', res)
    })
    // this.queyEnumByTableName();
  },
  computed: {
    regions () {
      return this.$store.state.common.regions
    }
  },
  methods: {
    async updateCodeStatus () {
      const res = await debugUpdate({ command: this.launchCode, on: true })
      if (!res[0]) {
        this.$message.success('使用成功')
      }
    },
    async onoffCodeStatus (status) {
      await debugUpdate({ command: this.launchCode, on: status })
      this.launchCodeStatus = status
    },
    async randomCode () {
      let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      let maxPos = chars.length
      var code = ''
      for (let i = 0; i < 6; i++) {
        code += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      this.launchCode = code
    },
    async launchAdd () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (!this.form.downloadUrl) {
            this.$message.error('安装包不能为空')
            return
          }
          const res = await launchAdd({ ...this.form, type: this.launchType })
          this.$message[res[0] ? 'error' : 'success'](
            res[0] ? '操作失败' : '操作成功'
          )
          this.getDataList()
          this.dialogFormVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    selectCancel () {
      this.onlineStuVisible = false
      this.getDataList()
    },
    onlineStuVisibleFn (index, record) {
      console.log(index, record)
      this.selectLaunch = record.id
      this.onlineStuVisible = true
    },
    async selectChange (val) {
      let classList = []
      for (let index = 0; index < val.length; index++) {
        const element = val[index]
        for (let i = 0; i < element.gradeList.length; i++) {
          const res = element.gradeList[i]
          for (let c = 0; c < res.checkedData.length; c++) {
            const classId = res.checkedData[c]
            classList.push({
              classesId: classId,
              gradeId: res.gradeId,
              schoolId: res.schoolId
            })
          }
        }
      }
      if (!classList.length) {
        this.$message.error('班级不能为空')
      } else {
        const updateRes = await onlineLaunch({
          classesLists: classList,
          launchId: this.selectLaunch
        })
        if (updateRes[0]) {
          this.$message.error(updateRes[1].message)
        } else {
          this.$message.success('上线成功')
          this.selectLaunch = null
          this.onlineStuVisible = false
          const launchList = await getLaunchList({
            page: this.pagination.pageNum,
            pageSize: this.pagination.pageSize,
            type: this.launchType
          })
          this.launchList = launchList[1].data
        }
      }
      console.log(val)
    },
    async getDataList (nurseryGrade, juniorGrade, middleGrade, highGrade) {
      const launchInfo = await getLaunchInfo({
        type: this.launchType
      })
      const launchList = await getLaunchList({
        page: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        type: this.launchType
      })
      const schoolList = await getSchoolList({
        page: this.schoolPagination.pageNum,
        pageSize: this.schoolPagination.pageSize,
        type: this.launchType
      })
      this.launchInfo = launchInfo[1].data || {}
      this.pagination.total = +launchList[1].total
      this.launchList = launchList[1].data
      this.schoolList = schoolList[1].data
      this.schoolPagination.total = +schoolList[1].total
    },
    async onSubmit () {
      this.schoolPagination.pageNum = 1
      const schoolList = await getSchoolList({
        page: this.schoolPagination.pageNum,
        pageSize: this.schoolPagination.pageSize,
        type: this.launchType,
        schoolName: this.search.name
      })
      this.schoolList = schoolList[1].data
      this.schoolPagination.total = +schoolList[1].total
    },
    // 批量导入
    async importObj (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'APK')
      if (res[0]) {
        return
      }
      this.form.downloadUrl = res[1].data.url
      this.fileName = res[1].data.fileName
      this.uploadLoading = false
      // this.$ref.uploadExl.clearFiles();
    },
    // 上传封面前验证
    beforeUploadImg (file) {
      console.log('file.type', file.type)
      this.uploadLoading = true
      const isExcel = file.type === 'application/vnd.android.package-archive'
      const isLt100M = file.size / 1024 / 1024 < 200
      if (!isExcel || !~file.name.indexOf('.apk')) {
        this.$message.error('上传的文件只能是 apk 格式!')
        this.uploadLoading = false
      }
      if (!isLt100M) {
        this.$message.error('上传的文件大小不能超过 200MB!')
        this.uploadLoading = false
      }
      return true
    },
    async handleCurrentChange (val) {
      this.pagination.pageNum = val
      const launchList = await getLaunchList({
        page: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        type: this.launchType
      })
      this.pagination.total = +launchList[1].total
      this.launchList = launchList[1].data
    },
    async handleSizeChange (val) {
      this.pagination.pageSize = val
      const launchList = await getLaunchList({
        page: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        type: this.launchType
      })
      this.pagination.total = +launchList[1].total
      this.launchList = launchList[1].data
    },
    async handleCurrentChangeSchool (val) {
      this.schoolPagination.pageNum = val
      const schoolList = await getSchoolList({
        page: this.schoolPagination.pageNum,
        pageSize: this.schoolPagination.pageSize,
        type: this.launchType,
        schoolName: this.search.name
      })
      this.schoolList = schoolList[1].data
      this.schoolPagination.total = +schoolList[1].total
    },
    async handleSizeChangeSchool (val) {
      this.schoolPagination.pageSize = val
      const schoolList = await getSchoolList({
        page: this.schoolPagination.pageNum,
        pageSize: this.schoolPagination.pageSize,
        type: this.launchType,
        schoolName: this.search.name
      })
      this.schoolList = schoolList[1].data
      this.schoolPagination.total = +schoolList[1].total
    },
    viewSchool (row) {
      this.$router.push({
        name: 'launch-school-detail',
        query: { id: row.schoolId }
      })
    },
    viewApp (row) {
      this.$router.push({
        name: 'launch-app-stu'
        // params: { id: row.id },
      })
    }
  }
}
</script>
<style scoped>
.select-box-left {
  float: left;
}
.info-box {
  display: flex;
  text-align: center;
}
.left {
  display: inline-block;
  width: 105px;
  text-align: left;
}
.left-main {
  width: 180px;
  display: inline-block;
  word-break: break-all;
  vertical-align: text-top;
}
.right {
  display: inline-block;
  width: 100px;
  text-align: left;
}
.info-box div {
  flex: 1;
}
.u-btn-box {
  display: flex;
}
.u-btn {
  font-size: 12px;
}
</style>
